package br.com.edoc.filter;




import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import br.com.edoc.controller.portal.PortalController;


public class ControleUsuario implements PhaseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4652697903762033153L;

	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();  
		String currentPage = facesContext.getViewRoot().getViewId();  

		boolean isLoginPage = (currentPage.lastIndexOf("/login/login.xhtml") > -1);  
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
		if(session !=null){
			PortalController portal = (PortalController) session.getAttribute("portal");  

			if (!isLoginPage && (portal==null || portal.getUsuario()==null)) {  
				NavigationHandler nh = facesContext.getApplication().getNavigationHandler();  
				nh.handleNavigation(facesContext, null, "logoff");  
			}  
		}else{
			NavigationHandler nh = facesContext.getApplication().getNavigationHandler();  
			nh.handleNavigation(facesContext, null, "logoff");
		}

	}

	public void beforePhase(PhaseEvent event) {
		  
	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}